package com.tfj.comm.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.WindowManager;

import com.hyphenate.chat.EMClient;
import com.hyphenate.tfj.DemoHelperChat;
import com.hyphenate.tfj.R;
import com.hyphenate.tfj.conference.ConferenceActivity;
import com.hyphenate.tfj.live.common.DemoHelper;
import com.hyphenate.tfj.live.common.OnResourceParseCallback;
import com.hyphenate.tfj.live.common.PreferenceManager;
import com.hyphenate.tfj.live.data.UserRepository;
import com.hyphenate.tfj.live.data.model.User;
import com.hyphenate.tfj.live.ui.MainActivity;
import com.hyphenate.tfj.live.ui.base.BaseLiveActivity;
import com.hyphenate.tfj.live.ui.other.viewmodels.LoginViewModel;
import com.hyphenate.tfj.ui.LoginActivity;
import com.hyphenate.tfj.ui.VideoCallActivity;
import com.hyphenate.tfj.ui.VoiceCallActivity;
import com.hyphenate.util.EasyUtils;
import com.tfj.mvp.tfj.per.logreg.VLogActivity;
import com.tfj.utils.AuthPreferences;

import androidx.lifecycle.ViewModelProvider;

/**
 * Created by xiaoqiang on 2017/12/25.
 */

public class SplashActivity extends BaseLiveActivity {
    private int height_statusbar = 0;
    private final int SPLASH_DISPLAY_LENGHT = 1000;
    private Handler handler;
    private LoginViewModel viewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setTheme(R.style.LaunchTheme);
        //setContentView(R.layout.__activity_splash);
        UserRepository.getInstance().init(this);

        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        handler = new Handler();
        // 延迟SPLASH_DISPLAY_LENGHT时间然后跳转到MainActivity
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                //skipToTarget();
                String ifFirst = AuthPreferences.getFirst();
                String userToken = AuthPreferences.getUserToken();
                String topActivityName = EasyUtils.getTopActivityName(EMClient.getInstance().getContext());
                if (topActivityName != null && (topActivityName.equals(VideoCallActivity.class.getName()) || topActivityName.equals(VoiceCallActivity.class.getName()) || topActivityName.equals(ConferenceActivity.class.getName()))) {
                    // nop
                    // avoid main screen overlap Calling Activity
                }else{
                    startActivity(new Intent(SplashActivity.this, HomePageActivity.class));
                    SplashActivity.this.finish();
                    overridePendingTransition(R.anim.ap2, R.anim.ap1);// 淡出淡入动画效果
                }
            }

                //}
//                if (TextUtils.isEmpty(ifFirst) || ifFirst.equals("1")) {
//                    //下载后第一次打开app
//                    startActivity(new Intent(SplashActivity.this, WelcomeGuideActivity.class));
//                    overridePendingTransition(R.anim.ap2, R.anim.ap1);// 淡出淡入动画效果
//                } else if(ifFirst.equals("0")){
//                    //下载后不是第一次打开app
//                    startActivity(new Intent(SplashActivity.this, HomePageActivity.class));
//                    overridePendingTransition(R.anim.ap2, R.anim.ap1);// 淡出淡入动画效果
//                }
        }, SPLASH_DISPLAY_LENGHT);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.__activity_splash;
    }

    private static final int sleepTime = 2000;
    @Override
    protected void onStart() {
        super.onStart();
        new Thread(new Runnable() {
            public void run() {
                if (DemoHelperChat.getInstance().isLoggedIn()) {
                    // auto login mode, make sure all group and conversation is loaed before enter the main screen
                    long start = System.currentTimeMillis();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    EMClient.getInstance().groupManager().loadAllGroups();
                    long costTime = System.currentTimeMillis() - start;
                    //wait
                    if (sleepTime - costTime > 0) {
                        try {
                            Thread.sleep(sleepTime - costTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
    });}

    //在SplashActivity中禁用返回键：
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }
    private void skipToTarget() {
        //登录过
        if(EMClient.getInstance().isLoggedInBefore()){
            PreferenceManager.init(mContext, EMClient.getInstance().getCurrentUser());
            DemoHelper.saveUserId();
            DemoHelper.initDb();
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }else {
            if(DemoHelper.isCanRegister()) {
                startActivity(new Intent(this, VLogActivity.class));
                finish();
            }else {
                //创建临时账号
                createRandomUser();
            }

        }
    }
    private void createRandomUser() {
        ProgressDialog pd = new ProgressDialog(mContext);
        pd.setMessage("请稍等...");
        pd.setCanceledOnTouchOutside(false);

        viewModel.getLoginObservable().observe(mContext, response -> {
            parseResource(response, new OnResourceParseCallback<User>() {
                @Override
                public void onSuccess(User data) {
                    skipToTarget();
                }

                @Override
                public void onLoading() {
                    super.onLoading();
                    pd.show();
                }

                @Override
                public void hideLoading() {
                    super.hideLoading();
                    pd.dismiss();
                }
            });
        });

        viewModel.login();
    }
}
